package com.dfbz.filter;

import com.dfbz.entity.User;
import com.dfbz.service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    private UserService userService = new UserService();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String targetName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        if (
                targetName.startsWith("/bootstrap") ||
                        targetName.startsWith("/css") ||
                        targetName.startsWith("/fonts") ||
                        targetName.startsWith("/img") ||
                        targetName.startsWith("/js") ||


                        targetName.equals("checkCode.jsp") ||
                        targetName.equals("index.jsp") ||
                        targetName.equals("taglib.jsp") ||
                        targetName.equals("register.jsp") ||
                        targetName.equals("login") ||
                        targetName.equals("checkEmail") ||
                        targetName.equals("checkUsername") ||
                        targetName.equals("register") ||
                        targetName.equals("wx_login")


        ) {
            filterChain.doFilter(request, response);
            return;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("loginUser") != null) {
            filterChain.doFilter(request, response);
            return;
        }
        Cookie temp = null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("loginUser")){
                    temp = cookie;
                    break;
                }
            }
        }
        if(temp != null){
            Long id = Long.parseLong(temp.getValue());
            User user = userService.findUserById(id);
            session.setAttribute("loginUser",user);
            filterChain.doFilter(request, response);
            return;
        }
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

    @Override
    public void destroy() {

    }
}
